package com.bst.etl.batch.dao;

import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.repository.dao.JdbcStepExecutionDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.lang.reflect.Constructor;
import java.util.List;

public class JdbcStepExecutionExDao extends JdbcStepExecutionDao {
    private static String sql = "SELECT STEP_EXECUTION_ID, STEP_NAME, START_TIME, END_TIME, " +
            "STATUS, COMMIT_COUNT, READ_COUNT, FILTER_COUNT, WRITE_COUNT, EXIT_CODE, EXIT_MESSAGE, READ_SKIP_COUNT, " +
            "WRITE_SKIP_COUNT, PROCESS_SKIP_COUNT, ROLLBACK_COUNT, LAST_UPDATED, VERSION from %PREFIX%STEP_EXECUTION " +
            "where JOB_EXECUTION_ID = ?";
    private JdbcStepExecutionExDao(){};

    private static volatile JdbcStepExecutionExDao executionExDao;

    public static JdbcStepExecutionExDao getInstance(JdbcTemplate jdbcTemplate) {
        if(executionExDao==null) {
            synchronized (JdbcJobExecutionExDao.class) {
                if(executionExDao==null) {
                    executionExDao = new JdbcStepExecutionExDao();
                }
            }
        }
        executionExDao.setJdbcTemplate(jdbcTemplate);
        return executionExDao;
    }

    public List<StepExecution> getStepExecution(JobExecution jobExecution) {
        try {
            Class[] declaredClasses = JdbcStepExecutionDao.class.getDeclaredClasses();
            Class declaredClass = declaredClasses[0];
            Constructor[] declaredConstructors = declaredClass.getDeclaredConstructors();
            Constructor declaredConstructor = declaredConstructors[0];
            declaredConstructor.setAccessible(true);
            RowMapper o = (RowMapper) declaredConstructor.newInstance(jobExecution);
            List<StepExecution> executions = super.getJdbcTemplate().query(getQuery(sql), o, jobExecution.getId());
            if (!executions.isEmpty()) {
                return executions;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


}
